﻿// --------------
// 作者:Vitity
// --------------

namespace NICWebApi.Extensions.DynamicAPI.Filter;

/// <summary>
/// Swagger操作过滤器，用于自定义Swagger文档的生成
/// </summary>
public class SwaggerOperationFilter : IOperationFilter
{
    /// <summary>
    /// 应用操作过滤器，用于自定义Swagger文档的生成
    /// </summary>
    /// <param name="operation">Swagger操作</param>
    /// <param name="context">操作过滤器上下文</param>
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (operation == null || context == null || context.MethodInfo == null)
            return;

        try
        {
            var method = context.MethodInfo;
            
            // 尝试获取操作元数据
            if (!Utils.ActionDict.TryGetValue(method, out var meta) || meta == null)
                return;

            // 如果特性中定义了Description属性，则将其添加到operation的Description中
            if (!string.IsNullOrWhiteSpace(meta.Description))
            {
                operation.Description = meta.Description;
            }

            // 如果特性中定义了DisplayName属性，则将其设置为operation的Summary
            if (!string.IsNullOrWhiteSpace(meta.DisplayName))
            {
                operation.Summary = meta.DisplayName;
            }

            // 处理过时API标记
            if (method.IsDefined(typeof(ObsoleteAttribute), true))
            {
                var deprecated = method.GetCustomAttribute<ObsoleteAttribute>(true);
                if (deprecated != null)
                {
                    // 标记为已弃用
                    operation.Deprecated = true;
                    
                    // 添加弃用消息
                    if (!string.IsNullOrWhiteSpace(deprecated.Message))
                    {
                        operation.Description = string.IsNullOrEmpty(operation.Description)
                            ? $"<div class=\"deprecated\">{deprecated.Message}</div>"
                            : $"<div class=\"deprecated\">{deprecated.Message}</div><br/>{operation.Description}";
                    }
                }
            }
            
            // 确保操作有正确的标签
            if (!string.IsNullOrEmpty(meta.Controller) && 
                (operation.Tags == null || !operation.Tags.Any(t => t.Name == meta.Controller)))
            {
                operation.Tags = new List<OpenApiTag> { new OpenApiTag { Name = meta.Controller } };
            }
        }
        catch (Exception ex)
        {
            // 记录异常但不中断Swagger文档生成
            System.Diagnostics.Debug.WriteLine($"Error in SwaggerOperationFilter: {ex.Message}");
        }
    }
}